package com.callbell.cas.handler;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.callbell.cas.util.MD5Util;

/**
 * 更新密码控制器<br>
 * 
 * @author xlh
 * 
 */
@SuppressWarnings("deprecation")
public class UpdatePasswordController extends AbstractController {

	private static Logger logger = Logger.getLogger(UpdatePasswordController.class);

	/** jdbc模版对象 */
	private SimpleJdbcTemplate jdbcTemplate;

	/** 数据源 */
	private DataSource dataSource;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String username = ServletRequestUtils.getStringParameter(request, "username");
		String oldpassword = ServletRequestUtils.getStringParameter(request, "oldpassword");
		String newpassword = ServletRequestUtils.getStringParameter(request, "newpassword");
		String confirmpassword = ServletRequestUtils.getStringParameter(request, "confirmpassword");
		// 根据用户名查询原始密码 TODO
		List<Map<String, Object>> list = jdbcTemplate.queryForList("select u.password from user u where u.account=?", username);
		String queryPassword = null;
		if (list != null && list.size() > 0) {
			queryPassword = (String) list.get(0).get("password");
		}
		if (queryPassword == null || "".equals(queryPassword)) {
			response.getWriter().write("不存在该用户或该用户为域用户：" + username);
			return null;
		}
		if (!queryPassword.equals(MD5Util.toMD5(oldpassword))) {
			response.getWriter().write("原始密码不正确");
			return null;
		}
		if (oldpassword.equals(newpassword)) {
			response.getWriter().write("新密码不能和原始密码相同");
			return null;
		}
		if (!newpassword.equals(confirmpassword)) {
			response.getWriter().write("二次输入的新密码不一致");
			return null;
		}
		// 更新密码
		try {
			jdbcTemplate.update("update um_user u set u.pwd=? where u.user_code=?", new Object[] { MD5Util.toMD5(newpassword), username });
		} catch (Exception e) {
			logger.error(e);
			response.getWriter().write("修改数据库密码操作异常：" + e.getMessage());
			return null;
		}
		response.getWriter().write("ok");
		logger.debug("update user '" + username + "' success");
		return null;
	}

	public void setDataSource(final DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}

	protected final DataSource getDataSource() {
		return this.dataSource;
	}
}
